import path from 'path';
import schedule from 'node-schedule';
import bluebird from 'bluebird';
import cfg from '../cfg';
import log from '../log';
import * as util from '../util';

const {schedules: schedulesCfg} = cfg;

/**
 * 初始化
 */
function init() {
    util.resolve().then(() => {
        if (schedulesCfg.enable === undefined || schedulesCfg.enable) {
            bluebird.reduce(schedulesCfg.jobs, (total, item) => {
                if ((item.enable === undefined || item.enable) && item.fn) {
                    const file = path.join(__dirname, '../', item.fn);
                    log.info('file', file);
                    //eslint-disable-next-line
                    const {default: fn} = require(file);
                    schedule.scheduleJob(item.rule, fn);
                }
            }, 0);
        }
    });
}

export default init;
